<template>
  <a-modal :destroy-on-close="true" :mask-closable="false" title="编辑公告" :open="visible" :onCancel="onCancel"
    :width="800">
    <template #footer>
      <a-button key="save" :loading="modelRef.announceStatus === '2' && onSubmitLoading" @click="onSave"
        v-show="!isReadonly && modelRef.announceStatus === '2'">保存</a-button>
      <a-button key="back" @click="() => onCancel()">取消</a-button>
      <a-button key="submit" type="primary" :loading="modelRef.announceStatus !== '2' && onSubmitLoading"
        @click="onFinish" v-show="!isReadonly">提交</a-button>
    </template>
    <a-form>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="公告类型" v-bind="validateInfos.type">
            <a-select ref="select" v-model:value="modelRef.type" :disabled="isReadonly"
              :options="typeOptions"></a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="发布人" v-bind="validateInfos.printName">
            <a-input v-model:value="modelRef.printName" placeholder="请输入名称" :disabled="true" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="公告标题" v-bind="validateInfos.title">
            <a-input v-model:value="modelRef.title" placeholder="请输入名称" :disabled="isReadonly" />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-show="modelRef.type === '4'">
          <a-form-item label="选择通知人" v-bind="validateInfos.announcePerson">
            <span v-for="(item, index) in userList" :key="index" class="user-btn">
              {{ item?.username }}
              <CloseOutlined @click="() => { deleteUser(index) }" v-show="!isReadonly" />
            </span>
            <PlusCircleOutlined style="font-size: 24px;" @click="showUserSelectCancel" v-show="!isReadonly" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="6">
          <a-form-item label="定时发布">
            <a-switch v-model:checked="modelRef.ifTimedRelease" :disabled="isReadonly" @change="onTimedReleaseChange" />
          </a-form-item>
        </a-col>
        <a-col :span="6" v-show="modelRef.ifTimedRelease">
          <a-form-item v-bind="validateInfos.publishDate">
            <a-date-picker v-model:value="modelRef.publishDate" :disabled="isReadonly" />
          </a-form-item>
        </a-col>
        <a-col :span="8" v-show="modelRef.ifTimedRelease">
          <a-form-item label="时间选择" v-bind="validateInfos.publishTime">
            <a-time-picker v-model:value="modelRef.publishTime" format="HH:mm" :disabled="isReadonly" />
          </a-form-item>
        </a-col>

      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="附件">
            <a-upload action="" :before-upload="beforeUpload" :auto-upload="false" :file-list="fileList">
              <a-button :disabled="isReadonly">
                <upload-outlined></upload-outlined>
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <span>支持文档类型：doc、docx、xls、xlsx、ppt、pdf、txt、jpg、png、gif、rar、zip、mp3等格式上传（最大300M）</span>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="适用范围" v-bind="validateInfos.announceScope">
            <a-checkbox-group v-model:value="modelRef.announceScope" :disabled="isReadonly">
              <a-checkbox value="1" name="announceScope">邮件</a-checkbox>
              <a-checkbox value="2" name="announceScope">钉钉</a-checkbox>
              <a-checkbox value="3" name="announceScope">站内通知</a-checkbox>
            </a-checkbox-group>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="公告正文" v-bind="validateInfos.content">
            <a-textarea v-model:value="modelRef.content" :rows="4" :disabled="isReadonly" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
  <user-select-modal :visible="userSelectVisible" :onCancel="userSelectCancel"
    :onSubmit="userSelectSubmit"></user-select-modal>
</template>
<script lang="ts">
export default {
  name: "CreateForm"
}
</script>
<script lang="ts" setup>
import { PropType, reactive, ref, defineProps, computed, onMounted, watch } from "vue";
import { useI18n } from "vue-i18n";
import { message, Form } from 'ant-design-vue';
import { TableListItem, SelectOption, UserDataItem } from "../data.d";
import { UploadOutlined, PlusCircleOutlined, CloseOutlined } from '@ant-design/icons-vue';
import { uploadFile } from '@/utils/FileUpload'
import type { UploadProps } from 'ant-design-vue';
import UserSelectModal from "./UserSelectModal.vue";
import { getAnnouncementTypeList } from '../service'
import dayjs from "dayjs";

const useForm = Form.useForm;
const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  values: {
    type: Object as PropType<Partial<TableListItem>>,
    required: true
  },
  onCancel: {
    type: Function,
    required: true
  },
  onSubmitLoading: {
    type: Boolean,
    required: true
  },
  onSubmit: {
    type: Function as PropType<(values: TableListItem) => void>,
    required: true
  },
  operationType: {
    type: String,
    require: true
  }
})
const { t } = useI18n();
const userList = ref<UserDataItem[]>([]);
const userSelectVisible = ref(false)
const typeOptions = ref<SelectOption[]>([])
const fileList = ref<UploadProps['fileList'][]>(props.values.fileInfos || []);
// 表单值
let modelRef = reactive<TableListItem>({
  id: props.values.id || 0,
  type: props.values.type || '',
  announcePerson: props.values.announcePerson || [],
  title: props.values.title || '',
  url: props.values.url || '',
  printName: props.values.printName || '',
  publishDate: props.values.timedReleaseTime ? dayjs(props.values.timedReleaseTime, 'YYYY-MM-DD') : '',
  publishTime: props.values.timedReleaseTime ? dayjs(props.values.timedReleaseTime, 'HH:mm') : '',
  announceScope: props.values.announceScope || '',
  content: props.values.content || '',
  ifTimedRelease: props.values.ifTimedRelease,
  announceStatus: props.values.announceStatus || '',
});
// 表单验证
const rulesRef = reactive({
  type: [
    {
      required: true,
      message: '公告类型不能为空'
    }
  ],
  title: [
    {
      required: true,
      message: '公告标题不能为空'
    }
  ],
  announceScope: [

    {
      required: true,
      message: '试用范围不能为空',
    },
  ],
  announcePerson: [
    {
      validator: () => {
        if (modelRef.type === '4' && userList.value.length < 1) {
          return Promise.reject('请选择通知人');
        }
        return Promise.resolve();
      }
    }
  ],
  content: [
    {
      required: true,
      message: '英文名称不能为空'
    }
  ],
  publishDate: [
    {
      required: modelRef.ifTimedRelease,
      message: '发布日期'
    }
  ],
  publishTime: [
    {
      required: modelRef.ifTimedRelease,
      message: '发布日期'
    }
  ],
});


const isReadonly = computed(() => props.operationType === 'view');

// 获取表单内容
const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef);

onMounted(() => {
  if (props.values) {
    const { announcePerson, announcePersonNames } = props.values;
    userList.value = announcePerson ? announcePerson.map((item: string, index) => ({ id: item, username: announcePersonNames ? announcePersonNames[index] : '' })) : [];
  }
  const username = localStorage.getItem('username') || '';
  rulesRef.publishDate = [
    {
      required: props.values.ifTimedRelease || false,
      message: '发布日期'
    }
  ],
    rulesRef.publishTime = [
      {
        required: props.values.ifTimedRelease || false,
        message: '发布日期'
      }
    ]
  modelRef.printName = username;
  getTypeList();
});
const deleteUser = (index: number) => {
  userList.value.splice(index, 1);
}
const showUserSelectCancel = () => {
  userSelectVisible.value = true;
}
const userSelectCancel = (val: boolean) => {
  userSelectVisible.value = val;
}
const userSelectSubmit = async (values: any) => {
  userList.value = values;
  userSelectVisible.value = false;

}
const onTimedReleaseChange = (val: boolean) => {
  rulesRef.publishDate = [
    {
      required: val,
      message: '发布日期不能为空'
    }
  ]
  rulesRef.publishTime = [
    {
      required: val,
      message: '发布时间不能为空'
    }
  ]
}
// 获取公告类型列表
const getTypeList = async (): Promise<void> => {
  const res = await getAnnouncementTypeList();
  if (res.success) {
    typeOptions.value = res.data.map(item => ({ label: item.value, value: item.code }))
  }
};

// 保存
const onSave = async () => {
  try {
    // const fieldsValue = await validate<Omit<TableListItem, 'id'>>();
    modelRef.announceStatus = '2'
    modelRef.announcePerson = userList.value.map(item => item.id)
    props.onSubmit(modelRef);
  } catch (error) {
    message.warning(t('app.global.form.validatefields.catch'));
  }
}
// 提交
const onFinish = async () => {
  try {
    const fieldsValue = await validate<Omit<TableListItem, 'id'>>();
    modelRef.announceStatus = modelRef.ifTimedRelease ? '3' : '1'
    modelRef.announcePerson = userList.value.map(item => item.id)
    props.onSubmit(modelRef);
  } catch (error) {
    message.warning(t('app.global.form.validatefields.catch'));
  }
};
const beforeUpload = async (file: any) => {
  const formData = new FormData()
  formData.append('file', file);
  formData.append('appId', 'admin-service');
  const res = await uploadFile(formData)
  if (res.data.success) {
    fileList.value = [file]
    modelRef.fileIds = [res.data.data.fileId]
  }
  return Promise.reject();
};

</script>
<style lang="less" scoped>
.user-btn {
  display: inline-block;
  padding: 4px;
  margin: 0 8px;
  background: rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(5, 5, 5, 0.06);
  border-radius: 4px;
}

::v-deep(.ant-form-item-label) {
  width: 90px !important;
}
</style>
